package org.example.viteVantDemo.security;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.example.viteVantDemo.Application;
import org.example.viteVantDemo.entity.UserInfo;
import org.example.viteVantDemo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * UserDetailsService实现类
 *
 * @author tnar
 *
 */
@Service
public class VantUserDetailsServiceImpl implements UserDetailsService {
    private static final String SUPPER_ADMIN = "super_admin";
    @Autowired
    private UserMapper userMapper;

    @Autowired
    public PasswordEncoder passwordEncoder;
    /**
     * 此函数为： authenticationManager.authenticate(upToken) 内部调用 ;
     * 需返回 用户信息载体 / 用户密码  。
     * 用户角色+权限的封装集合 (暂时不查询， 在验证通过后再次查询，避免用户名密码输入有误导致查询资源浪费)
     **/
    @Override
    public UserDetails loadUserByUsername(String loginUsernameStr) throws UsernameNotFoundException {
        LambdaQueryWrapper<UserInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserInfo::getName, loginUsernameStr);
        if (!SUPPER_ADMIN.equals(loginUsernameStr)) {
            wrapper.eq(UserInfo::getVersion, Application.getVersion());
        }
        List<UserInfo> userInfos = userMapper.selectList(wrapper);
        if (userInfos.size() == 0) {
            throw new UsernameNotFoundException("账号不存在");
        }
        UserInfo userInfo = userInfos.get(0);

        VantUser user = new VantUser();
        user.setId(userInfo.getId());
        user.setAvatar(userInfo.getAvatar());
        user.setUsername(loginUsernameStr);
        user.setPassword(passwordEncoder.encode("123456"));
        user.setVersion(userInfo.getVersion());
        return new VantUserDetails(user, user.getPassword());
    }
}
